<template>
  <div>
    <!-- 仅处理授权逻辑，无UI -->
  </div>
</template>

<script>
export default {
  created() {
    this.handleWechatAuth()
  },
  methods: {
    handleWechatAuth() {
      // 从URL参数获取code
      const urlParams = new URLSearchParams(window.location.search)
      const code = urlParams.get('code')

      if (code) {
        // ✅ 成功获取到 code
        console.log('获取到的code:', code)

        // 将code传递给父组件/全局状态
        this.$emit('got-code', code)

        // 跳转到原页面（可选）
        const target = localStorage.getItem('wx_redirect') || '/'
        this.$router.replace(target)
      } else {
        // ❌ 没有code，触发授权跳转
        this.redirectToWechatAuth()
      }
    },

    redirectToWechatAuth() {
      // 存储当前路径（用于授权后返回）
      localStorage.setItem('wx_redirect', this.$route.fullPath)

      // 构造授权URL
      const appid = 'wxc0e0c0644a34e28b' // 替换你的公众号appid
      const redirectUri = encodeURIComponent(
        window.location.origin + '/config' // 当前组件路径作为回调
      )

      // 微信授权链接 (scope=snsapi_base)
      const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`

      // 跳转到微信授权页
      window.location.href = authUrl
    }
  }
}
</script>
